<?php
session_start();
require 'connection.php';
require 'util.php';
require 'profileListingEditors.php';
checkLoggedIn();
$addionalInfoExists = additionalInformationExists($_SESSION['userLoggedIn']);

if(isset($_POST["action"])){
	executeAction($_POST, $_POST["action"], $addionalInfoExists);
}else{
	returnHome();
}
function returnHome(){
	goToUrl(getURLFromReferer("home.php"));
}

function executeAction($p, $action, $addionalInfoExists){
	switch($action){
		case "requestProfile":
			sendProfile($addionalInfoExists);
			break;
		case "showProfile":
			showProfile();
			break;
		case "getProfileEditor":
			getEditProfile();
			break;
		case "getProfileImagesEditor":
			getProfileImagesEditor();
			break;
		case "getResultImagesEditor":
			getResultImagesEditor();
			break;
		case "getListingEditor":
			getListingEditor();
			break;
		case "getLEPersonal"://LE = ListingEditor
			getLEPersonal();
			break;
		case "getLEHotel":
			getLEHotel();
			break;
		case "getLERestaurant":
			getLERestaurant();
			break;
		case "getLEBar":
			getLEBar();
			break;
		case "getLEEntertainment":
			getLEEntertainment();
			break;
		case "updateListing":
			saveListing($_POST, $_FILES);
			break;
		case "getListingTypeSelector":
			getListingTypeSelector();
			break;
		default:
			returnHome();
			break;
	}
}

function getEditProfile(){
	$noPicUrl = $GLOBALS['noPicImgUrl'];
	$info = getUserInformation(getLoggedInUser());
	$firstName = $info['first_name'];
	$secondName = $info['second_name'];
	$firstLastname = $info['first_lastname'];
	$secondLastname = $info['second_lastname'];
	$postcode = $info['postcode'];
	$address = $info['address'];
	$gender = $info['gender'];
	$dateOfBirth = $info['date_of_birth'];
	//$dateOfBirth = formatDateString($dateOfBirth, 'm/d/Y', 'Y-m-d');
	$age = getAge($dateOfBirth);

	$firstImageUrl = getProfilePicture();
	$htmlResponse = "
		<div id=\"editProfileFormContainer\">
			<div id=\"CPFCTheEditForm\">
				<form name=\"editProfileForm\" enctype=\"multipart/form-data\" method=\"post\" action=\"accountValidator.php\" >
				<div id=\"CPFCEditName\">
					<div>
						<label for=\"firstName\">First Name:</label>
						<input id=\"firstName\" name=\"firstName\" type=\"text\" value=\"{$firstName}\"></input>
						<label for=\"secondName\">Second Name:</label>
						<input id=\"secondName\" name=\"secondName\" type=\"text\" value=\"{$secondName}\"></input>
					</div>
					<div>
						<label for=\"firstLastname\">First Family Name:</label>
						<input id=\"firstLastname\" name=\"firstLastname\" type=\"text\" value=\"{$firstLastname}\"></input>
						<label for=\"secondLastname\">Second Family Name:</label>
						<input id=\"secondLastname\" name=\"secondLastname\" type=\"text\" value=\"{$secondLastname}\"></input>
					</div>
				</div>
				<div id=\"CPFCEditAddress\">
					<p>Address (we won't make it public): </p>
					<div>
						<label for=\"postcode\">Postcode:</label>
						<input type=\"text\" name=\"postcode\" id=\"postcode\" value=\"{$postcode}\"></input>
					</div>
					<div>
						<label for=\"address\">Address: </label>
						<input type=\"text\" name=\"address\" id=\"address\" value=\"{$address}\"></input>
					</div>
				</div>
				<div id=\"CPFCEditAditionalInfo\">
					<p>Additional information: </p>
					<div>
						<div>
							<label for=\"gender\">Gender:</label>
							<input type=\"radio\" name=\"gender\" id=\"genderM\" value=\"1\" ".($gender == "Male" ? "checked":"").">Male</input>
							<input type=\"radio\" name=\"gender\" id=\"genderF\" value=\"2\" ".($gender == "Female" ? "checked":"").">Female</input>
						</div>
						<div>
							<label for=\"dateOfBirth\">Date of birth:</label>
							<input type=\"date\" name=\"dateOfBirth\" id=\"dateOfBirth\" value=\"{$dateOfBirth}\">
						</div>
					</div>
					<div>
						<label for=\"primaryImage\">Profile Image: </label>
						<div id=\"primaryImagePreviewer\" style=\"background-image: url('{$firstImageUrl}')\">
						</div>
						<a href=\"#\" id=\"editProfileImages\">Edit images</a>
					</div>
				</div>
				<input type=\"hidden\" value=\"editProfile\" name=\"action\" />
				</form>
			</div>
			<div id=\"CPFCTheButtons\">
				<a id=\"CPFCCompleteEdit\" href=\"#\" class=\"nextBackButton\">Submit</a>
				<a id=\"CPFCExitEditProfile\" href=\"#\" class=\"nextBackButton\">Cancel</a>
			</div>
		</div>
		";

	$response = array(
		"error" => false,
		"htmlString"=>$htmlResponse
		);
	echo getJSON($response);
}

function getProfileImagesEditor()
{
	$noPicUrl = $GLOBALS['noPicImgUrl'];
	$picturesUrl = getUserPictures(getLoggedInUser());
	foreach($picturesUrl as &$pictureInfo)
	{
		if(!file_exists($pictureInfo["picture_url"]))
		{			
			continue;
		}
		list($width, $height, $type, $attributes) = getimagesize($pictureInfo["picture_url"]);
		$pictureInfo["height"] = $height;
		$pictureInfo["width"] = $width;
		unset($pictureInfo);
	}
	//print_r($picturesUrl);
	$htmlResponse = "
		<div id=\"picture-uploader\">
			<div>
				<a href=\"#\" id=\"PU-add\" class=\"PU-button\"><i class=\"flaticon-round69\"></i> <span class=\"white-text\">Add a picture</span></a>
				<a href=\"#\" id=\"PU-cancel\" class=\"PU-button\"> <i class=\"flaticon-round71\"></i> <span class=\"white-text\">Back</span></a>
				<div>
					<div id=\"PU-current-selected-picture\">
					</div>
					<p>Current profile picture</p>
				</div>
			</div>

			<div>
				<div id=\"PU-Container\">
								<div id=\"PU-previewer\">

								</div>
								<div id=\"PU-additionalControl\" class=\"hideClass\">
									<a href=\"#\" id=\"cropSaver\" class=\"PU-button\"> <i class=\"flaticon-floppy20\"></i><span class=\"white-text\">Save</span></a>
									<a href=\"#\" id=\"cropCancel\" class=\"PU-button\"> <i class=\"flaticon-round73\"></i><span class=\"white-text\">Cancel</span></a>
								</div>
								<div id=\"PU-control\">									
									<a href=\"#\" id=\"PU-set\" class=\"PU-button\"><i class=\"flaticon-round68\"></i><span class=\"white-text\">Set as main</span></a>
									<a href=\"#\" class=\"PU-button\" id=\"PU-crop\"><i class=\"flaticon-crop16\"></i><span class=\"white-text\">Crop</span></a>
									<a href=\"#\" id=\"PU-delete\" class=\"PU-button\"><i class=\"flaticon-rounded61\"></i><span class=\"white-text\">Delete</span></a>
									
								</div>
								<div id=\"PU-thumbs-container\">
									<div id=\"PU-backButtonContainer\">
											<a href=\"#\" id=\"PU-back\" class=\"center-vertically\"><i class=\"flaticon-previous11\"></i> </a>
									</div>										
									<div id=\"PU-thumbs\">

									</div>	
									<div id=\"PU-nextButtonContainer\">
											<a href=\"#\" id=\"PU-next\" class=\"center-vertically\"><i class=\"flaticon-next15\"></i></a>
									</div>
								</div>
				</div>
			</div>
		</div>
		";

	$response = array(
		"error" => false,
		"htmlString"=>$htmlResponse,
		"picturesUrl"=>$picturesUrl
		);
	echo getJSON($response);
}

function getResultImagesEditor()
{
	$noPicUrl = $GLOBALS['noPicImgUrl'];
	$picturesUrl = getListingPictures(null, false, getListingId());
	foreach($picturesUrl as &$pictureInfo)
	{
		if(!file_exists($pictureInfo["picture_url"]))
		{			
			continue;
		}
		list($width, $height, $type, $attributes) = getimagesize($pictureInfo["picture_url"]);
		$pictureInfo["height"] = $height;
		$pictureInfo["width"] = $width;
		unset($pictureInfo);
	}
	//print_r($picturesUrl);
	$htmlResponse = "
		<div id=\"picture-uploader\">
			<div>
				<a href=\"#\" id=\"PU-add\" class=\"PU-button\"><i class=\"flaticon-round69\"></i> <span class=\"white-text\">Add a picture</span></a>
				<a href=\"#\" id=\"PU-cancel\" class=\"PU-button\"> <i class=\"flaticon-round71\"></i> <span class=\"white-text\">Back</span></a>
				<div>
					<div id=\"PU-current-selected-picture\">
					</div>
					<p>Current listing picture</p>
				</div>
			</div>

			<div>
				<div id=\"PU-Container\">
								<div id=\"PU-previewer\">

								</div>
								<div id=\"PU-additionalControl\" class=\"hideClass\">
									<a href=\"#\" id=\"cropSaver\" class=\"PU-button\"> <i class=\"flaticon-floppy20\"></i><span class=\"white-text\">Save</span></a>
									<a href=\"#\" id=\"cropCancel\" class=\"PU-button\"> <i class=\"flaticon-round73\"></i><span class=\"white-text\">Cancel</span></a>
								</div>
								<div id=\"PU-control\">									
									<a href=\"#\" id=\"PU-set\" class=\"PU-button\"><i class=\"flaticon-round68\"></i><span class=\"white-text\">Set as main</span></a>
									<a href=\"#\" class=\"PU-button\" id=\"PU-crop\"><i class=\"flaticon-crop16\"></i><span class=\"white-text\">Crop</span></a>
									<a href=\"#\" id=\"PU-delete\" class=\"PU-button\"><i class=\"flaticon-rounded61\"></i><span class=\"white-text\">Delete</span></a>
									
								</div>
								<div id=\"PU-thumbs-container\">
									<div id=\"PU-backButtonContainer\">
											<a href=\"#\" id=\"PU-back\" class=\"center-vertically\"><i class=\"flaticon-previous11\"></i> </a>
									</div>										
									<div id=\"PU-thumbs\">

									</div>	
									<div id=\"PU-nextButtonContainer\">
											<a href=\"#\" id=\"PU-next\" class=\"center-vertically\"><i class=\"flaticon-next15\"></i></a>
									</div>
								</div>
				</div>
			</div>
		</div>
		";

	$response = array(
		"error" => false,
		"htmlString"=>$htmlResponse,
		"picturesUrl"=>$picturesUrl
		);
	echo getJSON($response);
}

function sendProfile($addionalInfoExists){
	$htmlResponse = "";
	$response = true;
	if(!$addionalInfoExists){
		$htmlResponse = "
		<div id=\"completeProfileFormContainer\" class=\"loginLayerContentsBox\">
			<div id=\"CPFCTheForm\">
				<form name=\"completeProfileForm\" enctype=\"multipart/form-data\" method=\"post\" action=\"accountValidator.php\" >
				<p>We're almost done...</p>
				<div id=\"CPFCName\" class=\"CPFCformPart\">
					<p>Please tell us who you are:</p>
					<div>
						<label for=\"firstName\">First Name:</label>
						<input id=\"firstName\" name=\"firstName\" type=\"text\"/>
						<label for=\"secondName\">Second Name:</label>
						<input id=\"secondName\" name=\"secondName\" type=\"text\"><br>
					</div>
					<div>
						<label for=\"firstLastname\">First Family Name:</label>
						<input id=\"firstLastname\" name=\"firstLastname\" type=\"text\"/>
						<label for=\"secondLastname\">Second Family Name:</label>
						<input id=\"secondLastname\" name=\"secondLastname\" type=\"text\">
					</div>
				</div>
				<div id=\"CPFCAddress\" class=\"CPFCformPart\">
					<p>Please give us your address (we won't make it public): </p>
					<label for=\"postcode\">Postcode:</label>
					<input type=\"text\" name=\"postcode\" id=\"postcode\"/>
					<label for=\"address\">Address: </label>
					<input type=\"text\" name=\"address\" id=\"address\" />
				</div>
				<div id=\"CPFCAdditionalInfo\" class=\"CPFCformPart\">
					<p>Additional information: </p>
					<div>
						<label for=\"gender\">Gender:</label>
						<input type=\"radio\" name=\"gender\" id=\"genderM\" value=\"1\" checked>Male</input>
						<input type=\"radio\" name=\"gender\" id=\"genderF\" value=\"2\">Female</input>
					</div>
					<label for=\"dateOfBirth\">Date of birth:</label>
					<input type=\"date\" name=\"dateOfBirth\" id=\"dateOfBirth\"/>
				</div>

				<input type=\"hidden\" value=\"completeRegistration\" name=\"action\" />
				</form>
			</div>
			<div id=\"CPFCTheButtons\">
				<a id=\"CPFCBack\" href=\"#\" class=\"nextBackButton\"> < Back</a>
				<a id=\"CPFCNext\" href=\"#\" class=\"nextBackButton\">Next > </a>
				<a id=\"CPFCComplete\" href=\"#\" class=\"nextBackButton\">Submit</a>
			</div>
		</div>
		";
		$response = false;
	}else{
		$response = true;

	}
	$arr = array(
		'response' => $response,
		'htmlString' => $htmlResponse 
		);
	echo getJSON($arr);
}

function showProfile(){
	$error = false;
	$htmlProfile = getProfileHtml();
	$htmlListing = getHtmlListing();
	$html = "<div id=\"profileAndListingContainer\" class=\"loginLayerContentsBox\">".$htmlProfile.$htmlListing."</div>";
	//echo $htmlString;
	//$html = $htmlListing;
	//echo $html;
	$response = array(
		'error'=> $error,
		'htmlString'=> $html
		);
	echo json_encode($response);
	 json_last_error();
	//echo "{error: '".$error."', htmlString: '".$htmlString."'}";
}



function getProfileHtml(){
	$noPicUrl = $GLOBALS['noPicImgUrl'];
	$info = getUserInformation(getLoggedInUser());
	$firstName = $info['first_name'];
	$secondName = $info['second_name'];
	$firstLastname = $info['first_lastname'];
	$secondLastname = $info['second_lastname'];
	$postcode = $info['postcode'];
	$address = $info['address'];
	$gender = $info['gender'];
	$dateOfBirth = $info['date_of_birth'];
	$dateOfBirth = formatDateString($dateOfBirth, 'Y-m-d', 'm/d/Y');
	$age = getAge($dateOfBirth);

	$firstImageUrl = getProfilePicture();
	$htmlProfile =
	"<div id=\"profileContainer\">
		<div id=\"profileImageContainer\">
		<img src=\"".$firstImageUrl."\" />
		</div>
		<div id=\"profileInfoContainer\">
		<p>$firstName".($secondName == "" ? "": " $secondName") ." $firstLastname".($secondLastname == "" ? "": " $secondLastname")."</p>
		<a href=\"#\" id=\"editProfileButton\" class=\"formButtonClass grayButton2 \">Edit profile</a>
		</div>
	</div>
	";
	return $htmlProfile;
}

function getHtmlListing(){
	$listingExists = listingExists(getLoggedInUser());
	$htmlString = "";
	$error = false;
	if(!$listingExists)
	{
		$htmlString = "
		<div id=\"listingWrapper\">
			<h3>It seems you don't have a listing created yet.</h3>
			<a id=\"createListingButton\" href=\"#\">You can start creating your listing here.</a>
		</div>
		";
	}
	else
	{
		$listing = getListing(getLoggedInUser());
		$listing = $listing[0];
		//print_r($listing);
		$pk = $listing['pk'];
		$type = $listing['result_type_fk'];
		$title = $listing['title'];
		$image_url = getListingPicture();
		$telephone = $listing['telephone'];
		$description = $listing['description'];
		$price = $listing['price'];
		$user = $listing['user_fk'];
		$email = $listing['email'];
		$webpage = $listing['webpage'];
		$roomType = $listing['room_type_fk'];
		$bedType = $listing['bed_type_fk'];
		$accomodates = $listing['accomodates'];
		$bedrooms = $listing['bedrooms'];
		$beds = $listing['beds'];
		$extraPeople = $listing['extra_people'];
		$weekPrice = $listing['week_price'];
		$monthPrice = $listing['month_price'];
		$cancellationFee = $listing['cancellation_fee'];
		$rules = $listing['rules'];
		$cancellationType = $listing['cancellation_type_fk'];
		//$address = ($listing['house'] == "" ? "" : $listing['house']).($listing['street'] == "" ? "" : $listing['street']).($listing['district'] == "" ? "" : $listing['district']).($listing['city'] == "" ? "" : $listing['city']);
		$postcode = $listing['postcode'];
		$city = $listing['city'];
		$street = $listing['street'];
		$house = $listing['house'];
		$district = $listing['district'];
		$rating = $listing['rating'];
		$lat = $listing['lat'];
		$lng = $listing['lng'];
		$addressPk = $listing['addressPk'];
		$locationPk = $listing['locationPk'];
		$htmlString = "<div id=\"fullListingDisplayer\">
			<div id=\"listingInfo\">
			<div id=\"LIImage\">
				<img src=\"{$image_url}\">
			</div>
			<div id=\"LIContents\">
				<div id=\"LITitle\">
					<h2>{$title}</h2>
					<h2>{$price}</h2>
				</div>
				<div id=\"LIDescription\">

					<div id=\"LIAddress\">
						<h3>{$city}, {$district}, {$street}</h3>
					</div>

					<div id=\"LIDescription\">
						".
							displayTextIfExists($description, "Description")
							.displayTextIfExists($weekPrice, "Week Price")
							.displayTextIfExists($monthPrice, "Month Price")
							.displayTextIfExists($rules, "Rules")
							.displayTextIfExists($accomodates, "Accomodates")
							.displayTextIfExists($bedrooms, "Bedrooms")
							.displayTextIfExists($beds, "Beds")
							.displayTextIfExists($cancellationType, "Cancellation")
							.displayTextIfExists($cancellationFee, "Cancellation Fee")
							.displayTextIfExists($webpage, "Webpage")
						."

					</div>
				</div>
				<a id=\"createListingButton\" class=\"nextBackButton\" href=\"#\">Edit</a>
			</div>
		</div>
		</div>";
	}
	return $htmlString;
}

//Listing logic

function listingExists($user){
	$result = getListing($user);
	return !empty($result);
}


function saveListing($post, $files){
	$pdo = $GLOBALS['pdo'];
	$pk = $post['exant'];
	$isUpdate = listingExists(getLoggedInUser());
	try{
		$pdo->beginTransaction();
		$paramsCoords = array(
			":latitude"=>$post['lat'],
			":longitude"=>$post['lng']
			);
		if($isUpdate){
			$paramsWhere = array(
				":pk"=>$post['exantLocation']
				);
			$locationFk = executeUpdate("location", $paramsCoords, $paramsWhere, $pdo);
		}else{
			$locationFk = executeInsert("location", $paramsCoords, $pdo);
		}
		
		$paramsAddress = array(
			":postcode"=>$post['postcode'],
			":street"=>$post['street'],
			":district"=>$post['area'],
			":city"=>$post['city'],
			":house"=>$post['houseNumber'],
			":location_fk"=>$locationFk
			);
		if($isUpdate){
				$paramsWhere = array(
				":pk"=>$post['exantAddress']
				);
			unset($paramsAddress[":location_fk"]);
			$addressFk = executeUpdate("address", $paramsAddress, $paramsWhere, $pdo);
		}else{
			$addressFk = executeInsert("address", $paramsAddress, $pdo);
		}

		$params = array(
			":title"=> $post['name'],
			":description"=> $post['description'],
			":price"=> $post['price'],
			":user_fk"=> getLoggedInUser(),
			":result_type_fk"=> $post['listingType'],
			":telephone"=> $post['telephone'],
			":email"=> $post['email'],
			":webpage"=> $post['webpage'],
			":cancellation_fee"=> floatval($post['cancellationFee']),
			":rules"=> $post['rules'],
			":cancellation_type_fk"=> $post['cancellation'],
			":address_fk"=> $addressFk,
			);
		if(isset($post['bedType'])) $params[':bed_type_fk'] = $post['bedType'];
		if(isset($post['accomodates'])) $params[':accomodates'] = $post['accomodates'];
		if(isset($post['bedrooms'])) $params[':bedrooms'] = $post['bedrooms'];
		if(isset($post['beds'])) $params[':beds'] = $post['beds'];
		if(isset($post['extra_people'])) $params[':extra_people'] = $post['extra_people'];
		if(isset($post['week_price'])) $params[':week_price'] = $post['week_price'];
		if(isset($post['month_price'])) $params[':month_price'] = $post['month_price'];
		if(isset($post['rating'])) $params[':rating'] = trim($post['rating']) != "" ? intval($post['rating']) : 0;
		if(isset($post['room_type_fk'])) $params[':room_type_fk'] = $post['room_type_fk'];
		if($isUpdate){
			$paramsWhere = array(
			":pk"=>$post['exant']
			);
			unset($params[":address_fk"]);
			executeUpdate("result", $params, $paramsWhere, $pdo);
		}else{
			$listingPk = executeInsert("result", $params, $pdo);
		}
		
		$pdo->commit();
		$response = array(
			"error"=> false,
			"message" => "allOk"
			);
		echo getJSON($response);
	}catch(PDOException $e) {
		$pdo->rollback();
		echo $e;
		throw $e;
	}
}

function displayRoomTypes($type = ""){
	$rt = getListingRoomTypes();
	$types = "";
  	foreach ($rt as $key => $value) {
  		$pk = $value['pk'];
  		$description = $value['description'];
  		if($type != "" && $type == $pk){
  			$types .= "<option value='$pk' selected>$description</option>";
		}
		else{
			$types .= "<option value='$pk'>$description</option>";
		}
  		
  	}
  	return $types;
}

function displayBedTypes($type = ""){
	$rt = getListingBedTypes();	
	$roomTypes = "";
	foreach ($rt as $key => $value) {
		$pk = $value['pk'];
		$description = $value['description'];
		if($type != "" && $type == $pk){
			$roomTypes .= "<option value='$pk' selected>$description</option>";
		}
		else{
			$roomTypes .= "<option value='$pk'>$description</option>";
		}
  		
  	}

  	return $roomTypes;
}

function displayCancellationTypes($type = ""){
	$rt = getListingCancellationTypes();
	$cancellationTypes = "";
	foreach ($rt as $key => $value) {
	  	$pk = $value['pk'];
		$description = $value['description'];
		if($type != "" && $type == $pk){
			$cancellationTypes .= "<option value='$pk' selected>$description</option>";
		}
		else{
			$cancellationTypes .= "<option value='$pk'>$description</option>";
		}
  	}

  	return $cancellationTypes;
}

function displayListingCathegories($type = ""){
	$rt = getListingCathegories();
	$listingCathegories = "";
	foreach ($rt as $key => $value) {
		$pk = $value['pk'];
  		$description = $value['description'];
  		//echo "El type es: {$type} y el pk es {$pk}";
  		if($type != "" && $type == $pk){
  			//echo "Es seleccionado";
  			$listingCathegories .= "<option value='$pk' selected>$description</option>";
  		}else{
  			$listingCathegories .= "<option value='$pk'>$description</option>";
  		}
  		
  	}	

  	return $listingCathegories;
}

function displayGenders($gender = ""){
	$rt = getGenders();
	$genders = "";
	foreach ($rt as $key => $value) {
		$pk = $value['pk'];
  		$description = $value['description'];
  		if($gender != "" && $gender == $pk){
  			$genders .= "<input type=\"radio\" name=\"gender\" id=\"genderM\" value=\"$pk\" checked>$description</input>";
		}
		else{
			$genders .=  "<input type=\"radio\" name=\"gender\" id=\"genderM\" value=\"$pk\">$description</input>";
		}
  		
  	}	

  	return $genders;
}


?>